import 'package:fig/models/master_media_spider.dart';
import 'package:fig/sqlite/sql_manager.dart';
import 'package:fig/sqlite/table_master_media_spider.dart';
import 'package:fig/utils/config.dart';
import 'package:sqflite/sqflite.dart';

// 用户配置表
class TableConfig extends TableBase {
  // 表名
  static final String tableName = 'config';

  static final String columnMediaPool = "media_pool";
  static final String columnTheme = "app_theme";
  static final String columnAutoSpider = "auto_spider"; // 是否自动爬取

  @override
  createTable(Database db) {
    db.execute('''create table $tableName (
    ${TableBase.columnId} integer primary key,
    $columnMediaPool integer default(1),
    $columnAutoSpider integer default(0),
    $columnTheme integer default(1)
    )''');
  }

  updateSelectPool(int poolId) async {
    Database db = await SqlManager.getConfigDatabase();
    db.update(tableName, {'$columnMediaPool': poolId}, where: '${TableBase.columnId}=?', whereArgs: [1])
        .catchError((error) => print('updateSelectPool:$error'))
        .whenComplete(() => print('updateSelectPool done'));
  }

  updateAutoSpider(bool autoSpider) async {
    Database db = await SqlManager.getConfigDatabase();
    db.update(tableName, {'$columnAutoSpider': autoSpider ? 1 : 0}, where: '${TableBase.columnId}=?', whereArgs: [1])
        .catchError((error) => print('updateAutoSpider:$error'))
        .whenComplete(() => print('updateAutoSpider done'));
  }

  @override
  insertDefault(Database db) {
    db.rawInsert('''insert into $tableName ($columnMediaPool,$columnAutoSpider,$columnTheme) values (1,1,1)''');
  }

  // 初始化配置
  Future<void> initConfig(Database db) async {
    String rawSql = '''select pool.${TableMediaPool.columnApiUrl},config.${TableConfig.columnMediaPool},config.${TableConfig.columnAutoSpider} from ${TableConfig.tableName} config
     left join ${TableMediaPool.tableName} pool on config.${TableConfig.columnMediaPool}=pool.${TableBase.columnId}
     where config.${TableBase.columnId}=1''';
    // print('获取真正的数据库名称:$rawSql');
    List<Map<String, dynamic>> result = await db.rawQuery(rawSql);
    // print('查询结果:$result');

    Config.init(result[0]['${TableConfig.columnMediaPool}'], result[0]['${TableMediaPool.columnApiUrl}'], (result[0]['${TableConfig.columnAutoSpider}']) == 0 ? false : true);

    // 获取爬虫资源库
    db.query(TableMediaPool.tableName).then((spiders) {
      Config.spiderPool = spiders.map((spider) => MasterMediaSpider.fromMap(spider)).toList();
      print('爬虫库初始化完毕,总数据量(${Config.spiderPool.length})');
    });

    print('要爬取的Url:${Config.spiderUrl()} Id:${Config.selectedSpider()} 是否自动爬取:${Config.autoSpider()}');
  }

  // 获取存储的数据库
  Future<String> realDbName() async {
    return Config.spiderUrl().split('.')[1];
  }
}
